<?php
/**
 * JS_API支付demo
 * ====================================================
 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
 * 成功调起支付需要三个步骤：
 * 步骤1：网页授权获取用户openid
 * 步骤2：使用统一支付接口，获取prepay_id
 * 步骤3：使用jsapi调起支付
 * 
*/
   define('BASEPATH', str_replace("\\", "/", 'system'));
   include_once(getcwd()."/application/libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php");
   include_once(getcwd().'/application/config/database.php');
   
   $order_id    =  (int)$_GET['order_id'];
   
   /*获取openid*/
   if(!isset($_GET['code']))
   {
       $return_url = urlencode("http://wap.zxkj918.com/js_call.php?order_id=".$order_id);
       $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3c5437a8f56b384e&redirect_uri=".$return_url."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
       header("Location:$url");
   }else{
        
       $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3c5437a8f56b384e&secret=d54eef1638a1c094d33e15bf2d0b1f66&code=".$_GET['code']."&grant_type=authorization_code";
       $ch  = curl_init();
       curl_setopt($ch, CURLOPT_URL,$url);
       curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);   //返回原生的（Raw）输出
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //可以设置为验证站点
       $result = curl_exec($ch);
       curl_close($ch);//解析 得到openid,打开绑定页面 传openid
       $resource = json_decode($result);
       $open_id = trim($resource->openid);
   }
   
   
   
   /*链接数据库*/
   $db_host     =  $db['default']['hostname'].':'.$db['default']['port'];
   $db_database =  $db['default']['database'];
   $db_username =  $db['default']['username'];
   $db_password =  $db['default']['password'];
   $connection  =  mysqli_connect($db_host,$db_username,$db_password,$db_database);//连接到数据库
   mysqli_set_charset ($connection,'utf8mb4');//编码转化
   if(!$connection){
       die("could not connect to the database:</br>".mysqli_connect_error());//诊断连接错误
   }
   $result = mysqli_query($connection,"SELECT sales_order.order_sn,sales_order.order_pay_total,line_order_product.line_name FROM sales_order INNER JOIN line_order_product ON line_order_product.order_id = sales_order.order_id WHERE sales_order.order_id=".$order_id);//执行查询
   if($result === false)
   {
       die("could not to the database</br>".mysqli_error());
   }
   $orderData    =  mysqli_fetch_assoc($result);
   mysqli_free_result($result);
   $body         =  $orderData['line_name'];
   $total_fee    =  $orderData['order_pay_total']*100;
	//使用jsapi接口
   $jsApi        =  new JsApi_pub();	
   $unifiedOrder =  new UnifiedOrder_pub();
   $unifiedOrder->setParameter("openid","$open_id");//商品描述
   $unifiedOrder->setParameter("body","$body");//商品描述
   $timeStamp    =  time();
   $unifiedOrder->setParameter("out_trade_no","$order_id");//商户订单号 
   $unifiedOrder->setParameter("total_fee","$total_fee");//总金额   以分为单位
   $unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址 
   $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
   $prepay_id    =  $unifiedOrder->getPrepayId();
   //使用jsapi调起支付
   $jsApi->setPrepayId($prepay_id);
   $jsApiParameters = $jsApi->getParameters();
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>微信安全支付</title>
<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			<?php echo $jsApiParameters; ?>,
			function(res){
				WeixinJSBridge.log(res.err_msg);
				if(res.err_msg == "get_brand_wcpay_request:ok"){  //同步点击完成按钮  --成功					 
	                  window.location.href="http://wap.zxkj918.com/line/payment/wxCompletePay/"+<?php echo $order_id?>;
	             }else{ //--失败
                          //return alert(res.err_code+res.err_desc+res.err_msg);
	            	  window.location.href="http://wap.zxkj918.com/line/payment/wxCompletePay/"+<?php echo $order_id?>;
	             }
			}
		);
	}
	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	window.onload=callpay;
</script>
</head>
<body>
</body>
</html>